package frontend.admin;

import backend.EmptyOutput;
import backend.GeneralDatabase;
import service.DatabaseManager;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class UserTableComponents {
    private final UserTableModel tableModel;
    private final JTable table;
    private final JScrollPane scrollPane;
    static GeneralDatabase db=null;
    public UserTableComponents() {
        // 初始化模型
        tableModel = new UserTableModel();

        // 创建表格
        table = new JTable(tableModel);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));

        // 设置等级列渲染器（新增）
        table.getColumnModel().getColumn(2).setCellRenderer((table, value, isSelected, hasFocus, row, column) -> {
            JLabel label = new JLabel(value.toString(), SwingConstants.CENTER);
            label.setOpaque(true);
            label.setBackground(value.toString().equals("1") ? new Color(255, 204, 204) :
                    value.toString().equals("2") ? new Color(204, 255, 204) :
                            new Color(204, 204, 255));
            return label;
        });

        // 设置操作列渲染器和编辑器
        ActionButtonsRendererEditor buttonsRenderer = new ActionButtonsRendererEditor(tableModel);
        table.getColumnModel().getColumn(3).setCellRenderer((table, value, isSelected, hasFocus, row, column) ->
                buttonsRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column));
        table.getColumnModel().getColumn(3).setCellEditor(buttonsRenderer);

        // 滚动面板
        scrollPane = new JScrollPane(table);
    }

    public JScrollPane getScrollPane() {
        return scrollPane;
    }

    public void addUser(String username, String password, int level) {
        tableModel.addUser(username, password, level);
    }

    // 自定义表格模型
    private static class UserTableModel extends AbstractTableModel {
        private final String[] columnNames = {"账号", "密码", "权限等级", "操作"};
        private final List<User> users = new ArrayList<>();

        public UserTableModel() {
            try {
                GeneralDatabase db = DatabaseManager.getInstance();
                String[][] users = db.getAllUserinfos(); // 使用新方法
                for (String[] user : users) {
                    // 添加用户数据到模型
                    addUser(user[0], user[1],
                            Integer.parseInt(user[2]));
                }
            } catch (EmptyOutput e) {
                JOptionPane.showMessageDialog(null, "用户列表为空");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "数据库连接错误");
            }
        }
        private String getRoleName(int permission) {
            return switch (permission) {
                case 777 -> "管理员(777)";
                case 755 -> "普通用户(755)";
                default -> "自定义权限(" + permission + ")";
            };
        }

        public void addUser(String username, String password, int level) {
            users.add(new User(username, password, level));
            fireTableRowsInserted(users.size()-1, users.size()-1);
        }

        public void removeUser(int rowIndex) {
            if (rowIndex >= 0 && rowIndex < users.size()) {
                users.remove(rowIndex);
                fireTableRowsDeleted(rowIndex, rowIndex);
            }
        }

        public void updateRole(int rowIndex, String newRole) {
            if (rowIndex >= 0 && rowIndex < users.size()) {
                users.get(rowIndex).role = newRole;
                fireTableCellUpdated(rowIndex, 3);
            }
        }
        public void refreshData() {
            users.clear();
            try {
                GeneralDatabase db = DatabaseManager.getInstance();
                String[][] userData = db.getAllUserinfos();
                for (String[] user : userData) {
                    users.add(new User(user[0], user[1], Integer.parseInt(user[2])));
                }
                fireTableDataChanged(); // 触发全表数据更新
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "刷新数据失败: " + e.getMessage());
            }
        }

        @Override
        public int getRowCount() {
            return users.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        @Override
        public Object getValueAt(int row, int col) {
            User user = users.get(row);
            switch (col) {
                case 0: return user.username;
                case 1: return user.password;
                case 2: return user.level;
                case 3: return user.role;
                default: return null;
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 3;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnIndex == 3 ? JButton.class : Object.class;
        }

        // 用户数据模型
        private static class User {
            String username, password, role;
            int level;

            User(String username, String password, int level) {
                this.username = username;
                this.password = password;
                this.role = role;
                this.level = level;
            }
        }
    }

    // 操作列渲染器与编辑器
    private static class ActionButtonsRendererEditor extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {
        private final JButton editButton = new JButton("修改");
        private final JButton deleteButton = new JButton("删除");
        private final JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        private int currentRow = -1;
        private final UserTableModel model;

        public ActionButtonsRendererEditor(UserTableModel model) {
            this.model = model;
            setupButton(editButton, new Color(144, 238, 144), Color.WHITE); // 绿色
            setupButton(deleteButton, new Color(255, 99, 71), Color.WHITE); // 红色
            panel.add(editButton);
            panel.add(deleteButton);

            // 按钮事件绑定
            editButton.addActionListener(e -> {
                try {
                    GeneralDatabase db = DatabaseManager.getInstance();
                    String newPermStr = JOptionPane.showInputDialog("输入新权限等级（777=管理员/755=普通用户）");
                    int newPerm = Integer.parseInt(newPermStr);
                    String targetUser = (String) model.getValueAt(currentRow, 0);

                    // 执行数据库修改
                    String result = db.tryUsermod("admin", targetUser, newPerm);
                    if ("SUCCESS".equals(result)) {
                        model.refreshData(); // 修改成功后刷新数据
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "修改失败: " + ex.getMessage());
                }
            });

            deleteButton.addActionListener(e -> {
                try {
                     db = DatabaseManager.getInstance();
                    String targetUser = (String) model.getValueAt(currentRow, 0);

                    if (JOptionPane.showConfirmDialog(
                            null,                    // 父组件
                            "确认执行此操作吗？",      // 消息内容
                            "操作确认",               // 标题
                            JOptionPane.OK_CANCEL_OPTION // 选项类型
                    ) == JOptionPane.OK_OPTION) {
                        db.tryUserdel("admin", targetUser); // 管理员操作
                        model.removeUser(currentRow);
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "删除失败：" + ex.getMessage());
                }
            });
        }

        private void setupButton(JButton button, Color bgColor, Color fgColor) {
            button.setBackground(bgColor);
            button.setForeground(fgColor);
            button.setFocusPainted(false);        // 禁用焦点边框
            button.setBorderPainted(false);       // 禁用边框绘制
            button.setContentAreaFilled(false);   // 防止默认背景干扰
            button.setOpaque(true);               // 确保颜色可以正确渲染
            button.setRolloverEnabled(false);     // 禁用悬停效果
            button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            currentRow = row;

            // 强制设置按钮颜色，避免受表格选中状态影响
            editButton.setBackground(new Color(144, 238, 144)); // 绿色
            deleteButton.setBackground(new Color(255, 99, 71)); // 红色

            // 设置 panel 背景色与表格一致
            panel.setBackground(table.getBackground());

            return panel;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            currentRow = row;

            // 同样重置按钮颜色，避免编辑状态下颜色变化
            editButton.setBackground(new Color(144, 238, 144));
            deleteButton.setBackground(new Color(255, 99, 71));

            // 设置 panel 背景色与表格一致
            panel.setBackground(table.getBackground());

            return panel;
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }
    }
}
